/**
 * @author p.stenzel
 */
var button = null;
var comPorts = [];
chrome.self.onConnect.addListener(function(port) {
	comPorts[port.tab.id] = port;
});

function registerHandlers()	{
	button = document.getElementById("button");
	button.addEventListener("click",handleClick);
	button.addEventListener("dblclick",handleDoubleClick);
	
	chrome.tabs.onSelectionChanged.addListener(function(cb)	{
		button.innerHTML = "Show largest image";
	})
}

function handleClick() {
	chrome.tabs.getSelected(null,function(tab)	{
		if (comPorts[tab.id]) {
			comPorts[tab.id].onMessage.addListener(function(images){
				if(images.length>0)	{
					chrome.tabs.update(tab.id,{url:images[0]});
				}	else	{
					button.innerHTML = "No images found";
				}
			});
			comPorts[tab.id].postMessage("fg");
		}
	})
}

function handleDoubleClick()	{
	var selected_tab = null;
	var process = false;
	chrome.tabs.getSelected(null,function(tab)	{
		selected_tab = tab.id;
	})
	chrome.windows.getCurrent(function(window)	{
		chrome.tabs.getAllInWindow(window.id,function(tabs)	{
			for(var key in tabs)	{
				var tab = tabs[key];
				if(tab.id==selected_tab)	process=true;
				if (process) {
//					console.log(tab.url);
					if (comPorts[tab.id]) {
//						comPorts[tab.id].onMessage.addListener(function(images){
//							console.log(tab.url+": "+images.length+" found");
//							if(images.length>0)	{
//								console.log(images[0]);
//								chrome.tabs.update(tab.id,{url:images[0]});
//							}	else	{
//								button.innerHTML = "No images found";
//							}
//						});
						comPorts[tab.id].postMessage("bg");
					}
				}
			}
		})
	})
}